using Auth.Application.DTO.Input;
using Auth.Application.DTO.Output;
using Auth.Domain.Entities;
using Auth.Infrastructure.Repositories;
using Auth.Result;
using AutoMapper;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace Auth.Application.Services
{
    /// <summary>
    /// 认证服务实现
    /// </summary>
    public class AuthService : IAuthService
    {
        private readonly IAuthRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;

        public AuthService(
            IAuthRepository<UserModel> userRepository,
            IMapper mapper,
            IConfiguration configuration)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _configuration = configuration;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>操作结果</returns>
        public ApiResult ChangePassword(long userId, string oldPassword, string newPassword)
        {
            if (string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword))
            {
                return new ApiResult
                {
                    Success = ResultCode.Fail,
                    Message = "密码不能为空"
                };
            }

            try
            {
                // 获取用户信息
                var user = _userRepository.GetById(userId);
                if (user == null)
                {
                    return new ApiResult
                    {
                        Success = ResultCode.Fail,
                        Message = "用户不存在"
                    };
                }

                // 验证旧密码
                string hashedOldPassword = HashPassword(oldPassword);
                if (!user.Password.Equals(hashedOldPassword))
                {
                    return new ApiResult
                    {
                        Success = ResultCode.Fail,
                        Message = "旧密码不正确"
                    };
                }

                // 更新密码
                user.Password = HashPassword(newPassword);
                user.UpdatedAt = DateTime.Now;
                user.UpdatedBy = user.UserName;

                int result = _userRepository.Update(user);

                return new ApiResult
                {
                    Success = result > 0 ? ResultCode.Success : ResultCode.Fail,
                    Message = result > 0 ? "密码修改成功" : "密码修改失败"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult
                {
                    Success = ResultCode.Fail,
                    Message = $"密码修改失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 生成JWT令牌
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>JWT令牌</returns>
        public string GenerateJwtToken(UserModel user)
        {
            if (user == null)
                throw new ArgumentNullException(nameof(user));

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                new Claim(JwtRegisteredClaimNames.Name, user.RealName ?? string.Empty),
                new Claim("role", user.RoleId ?? string.Empty),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddHours(double.Parse(_configuration["Jwt:ExpireHours"])),
                signingCredentials: credentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns>用户列表</returns>
        public ApiPaging<UserOutput> GetAllUsers(PageInput input)
        {
            var result = new ApiPaging<UserOutput>();
            
            try
            {
                var users = _userRepository.GetAll().Where(u => !u.IsDeleted).ToList();
                
                result.TotalCount = users.Count;
                result.TotalPages = (int)Math.Ceiling(result.TotalCount * 1.0 / input.PagingSize);
                result.CurrentPage = input.PagingIndex;
                result.PageSize = input.PagingSize;
                
                var pagedUsers = users
                    .OrderBy(u => u.Id)
                    .Skip((input.PagingIndex - 1) * input.PagingSize)
                    .Take(input.PagingSize)
                    .ToList();
                
                result.PagingData = _mapper.Map<List<UserOutput>>(pagedUsers);
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"Error getting all users: {ex.Message}");
            }
            
            return result;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户信息</returns>
        public ApiResult<UserOutput> GetUserInfo(long userId)
        {
            try
            {
                var user = _userRepository.GetById(userId);
                if (user == null || user.IsDeleted)
                {
                    return new ApiResult<UserOutput>
                    {
                        Success = ResultCode.NotFound,
                        Message = "用户不存在",
                        Data = null
                    };
                }

                var userOutput = _mapper.Map<UserOutput>(user);

                return new ApiResult<UserOutput>
                {
                    Success = ResultCode.Success,
                    Message = "获取用户信息成功",
                    Data = userOutput
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<UserOutput>
                {
                    Success = ResultCode.Fail,
                    Message = $"获取用户信息失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginInput">登录信息</param>
        /// <returns>登录结果</returns>
        public ApiResult<LoginOutput> Login(LoginInput loginInput)
        {
            if (loginInput == null)
            {
                return new ApiResult<LoginOutput>
                {
                    Success = ResultCode.Fail,
                    Message = "登录参数不能为空",
                    Data = null
                };
            }

            try
            {
                // 验证用户名
                var user = _userRepository.GetUserByUserName(loginInput.UserName);
                if (user == null || user.IsDeleted)
                {
                    return new ApiResult<LoginOutput>
                    {
                        Success = ResultCode.Fail,
                        Message = "用户名或密码不正确",
                        Data = null
                    };
                }

                // 验证密码
                string hashedPassword = HashPassword(loginInput.Password);
                if (!user.Password.Equals(hashedPassword))
                {
                    return new ApiResult<LoginOutput>
                    {
                        Success = ResultCode.Fail,
                        Message = "用户名或密码不正确",
                        Data = null
                    };
                }

                // 验证用户状态
                if (user.IsActive)
                {
                    return new ApiResult<LoginOutput>
                    {
                        Success = ResultCode.Fail,
                        Message = "用户已被禁用",
                        Data = null
                    };
                }

                // 更新最后登录时间
                user.LastLoginTime = DateTime.Now;
                _userRepository.Update(user);

                // 生成JWT令牌
                string token = GenerateJwtToken(user);
                int expireHours = int.Parse(_configuration["Jwt:ExpireHours"]);

                //// 构建登录结果
                var loginOutput = new LoginOutput
                {
                    UserId = user.Id,
                    UserName = user.UserName,
                    RealName = user.RealName,
                    RoleId = user.RoleId,
                    RoleName = user.RoleName,
                    Token = token,
                    ExpireIn = expireHours * 3600 // 转换为秒
                };

                var data= _mapper.Map<LoginOutput>(loginOutput);

                return new ApiResult<LoginOutput>
                {
                    Success = ResultCode.Success,
                    Message = "登录成功",
                    Data = data
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<LoginOutput>
                {
                    Success = ResultCode.Fail,
                    Message = $"登录失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="registerInput">注册信息</param>
        /// <returns>注册结果</returns>
        public ApiResult<int> Register(RegisterInput registerInput)
        {
            if (registerInput == null)
            {
                return new ApiResult<int>
                {
                    Success = ResultCode.Fail,
                    Message = "注册参数不能为空",
                    Data = 0
                };
            }

            try
            {
                // 检查用户名是否已存在
                var existingUser = _userRepository.GetUserByUserName(registerInput.UserName);
                if (existingUser != null)
                {
                    return new ApiResult<int>
                    {
                        Success = ResultCode.Fail,
                        Message = "用户名已存在",
                        Data = 0
                    };
                }

                // 创建新用户
                var user = new UserModel
                {
                    Id = GenerateSnowflakeId(),
                    UserName = registerInput.UserName,
                    Password = HashPassword(registerInput.Password),
                    RealName = registerInput.RealName,
                    UserCode = registerInput.UserCode,
                    Phone = registerInput.Phone,
                    RoleId = "user", // 默认角色
                    RoleName = "用户", // 默认角色名称
                    IsActive = true,
                    CreatedAt = DateTime.Now,
                    CreatedBy = "System"
                };

                int result = _userRepository.Create(user);

                return new ApiResult<int>
                {
                    Success = result > 0 ? ResultCode.Success : ResultCode.Fail,
                    Message = result > 0 ? "注册成功" : "注册失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Success = ResultCode.Fail,
                    Message = $"注册失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 密码哈希
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns>哈希后的密码</returns>
        private string HashPassword(string password)
        {
            using var sha256 = SHA256.Create();
            var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 生成雪花ID
        /// </summary>
        /// <returns>唯一ID</returns>
        private long GenerateSnowflakeId()
        {
            // 简化版雪花ID实现
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            long machineId = 1; // 机器ID
            long sequence = new Random().Next(0, 4095); // 序列号

            return ((timestamp - 1288834974657L) << 22) | (machineId << 12) | sequence;
        }
        /// <summary>
        /// /获取所有用户
        /// </summary>
        /// <returns></returns>
        public ApiResult<List<ShowUserDTO>> ShowUserData()
        {
            ApiResult<List<ShowUserDTO>> api=new ApiResult<List<ShowUserDTO>>();
            var data = _userRepository.GetAll();
            var list=_mapper.Map<List<ShowUserDTO>>(data);
            api.Data = list;
            return api;
        }
    }
} 